<template>
  <div class="photo-detail" v-if="photo">
    <div class="detail-header">
      <div class="photo-title">{{ photo.fileName }}</div>
      <div class="photo-actions">
        <el-button type="text" @click="openInFolder">
          <el-icon><FolderOpened /></el-icon>
          在文件夹中显示
        </el-button>
        <el-button type="text" @click="openWithDefaultApp">
          <el-icon><View /></el-icon>
          使用默认应用打开
        </el-button>
        <el-button 
          type="text" 
          :class="{ 'is-favorite': photo.rating > 0 }"
          @click="toggleFavorite"
        >
          <el-icon><Star /></el-icon>
          {{ photo.rating > 0 ? '取消收藏' : '收藏' }}
        </el-button>
      </div>
    </div>
    
    <div class="detail-content">
      <div class="photo-preview">
        <img 
          :src="getPreviewUrl(photo)" 
          :alt="photo.fileName"
          @load="handleImageLoad"
          @error="handleImageError"
        />
        <div class="image-loading-overlay" v-if="imageLoading">
          <el-icon class="is-loading"><Loading /></el-icon>
        </div>
      </div>
      
      <div class="photo-info">
        <el-tabs v-model="activeTab">
          <el-tab-pane label="基本信息" name="basic">
            <div class="info-section">
              <div class="info-item" v-if="photo.capturedAt">
                <div class="info-label">拍摄时间</div>
                <div class="info-value">{{ formatDateTime(photo.capturedAt) }}</div>
              </div>
              
              <div class="info-item" v-if="photo.createdAt">
                <div class="info-label">创建时间</div>
                <div class="info-value">{{ formatDateTime(photo.createdAt) }}</div>
              </div>
              
              <div class="info-item" v-if="photo.modifiedAt">
                <div class="info-label">修改时间</div>
                <div class="info-value">{{ formatDateTime(photo.modifiedAt) }}</div>
              </div>
              
              <div class="info-item">
                <div class="info-label">文件大小</div>
                <div class="info-value">{{ formatFileSize(photo.fileSize) }}</div>
              </div>
              
              <div class="info-item" v-if="photo.width && photo.height">
                <div class="info-label">尺寸</div>
                <div class="info-value">{{ photo.width }} × {{ photo.height }}</div>
              </div>
              
              <div class="info-item" v-if="photo.format">
                <div class="info-label">格式</div>
                <div class="info-value">{{ photo.format.toUpperCase() }}</div>
              </div>
              
              <div class="info-item">
                <div class="info-label">文件路径</div>
                <div class="info-value file-path" :title="photo.filePath">{{ photo.filePath }}</div>
              </div>
            </div>
          </el-tab-pane>
          
          <el-tab-pane label="相机信息" name="camera" v-if="hasCameraInfo">
            <div class="info-section">
              <div class="info-item" v-if="photo.cameraMake">
                <div class="info-label">制造商</div>
                <div class="info-value">{{ photo.cameraMake }}</div>
              </div>
              
              <div class="info-item" v-if="photo.cameraModel">
                <div class="info-label">型号</div>
                <div class="info-value">{{ photo.cameraModel }}</div>
              </div>
              
              <div class="info-item" v-if="exifInfo.focalLength">
                <div class="info-label">焦距</div>
                <div class="info-value">{{ exifInfo.focalLength }}mm</div>
              </div>
              
              <div class="info-item" v-if="exifInfo.aperture">
                <div class="info-label">光圈</div>
                <div class="info-value">f/{{ exifInfo.aperture }}</div>
              </div>
              
              <div class="info-item" v-if="exifInfo.shutterSpeed">
                <div class="info-label">快门速度</div>
                <div class="info-value">{{ exifInfo.shutterSpeed }}s</div>
              </div>
              
              <div class="info-item" v-if="exifInfo.iso">
                <div class="info-label">ISO</div>
                <div class="info-value">{{ exifInfo.iso }}</div>
              </div>
              
              <div class="info-item" v-if="exifInfo.flash">
                <div class="info-label">闪光灯</div>
                <div class="info-value">{{ exifInfo.flash ? '开启' : '关闭' }}</div>
              </div>
            </div>
          </el-tab-pane>
          
          <el-tab-pane label="位置信息" name="location" v-if="hasLocationInfo">
            <div class="info-section">
              <div class="info-item" v-if="photo.latitude && photo.longitude">
                <div class="info-label">GPS坐标</div>
                <div class="info-value">
                  {{ formatCoordinate(photo.latitude, photo.longitude) }}
                </div>
              </div>
              
              <div class="info-item" v-if="photo.altitude">
                <div class="info-label">海拔</div>
                <div class="info-value">{{ photo.altitude }}米</div>
              </div>
              
              <div class="map-container" v-if="photo.latitude && photo.longitude">
                <div class="map-placeholder">
                  <el-icon><Location /></el-icon>
                  <div>地图视图</div>
                  <div class="coordinates">{{ formatCoordinate(photo.latitude, photo.longitude) }}</div>
                </div>
              </div>
            </div>
          </el-tab-pane>
          
          <el-tab-pane label="描述" name="description">
            <div class="info-section">
              <div class="info-item">
                <div class="info-label">描述</div>
                <div class="info-value">
                  <el-input
                    v-model="photoDescription"
                    type="textarea"
                    :rows="4"
                    placeholder="添加照片描述..."
                    @blur="updateDescription"
                  />
                </div>
              </div>
              
              <div class="info-item">
                <div class="info-label">标签</div>
                <div class="info-value">
                  <el-tag
                    v-for="tag in photoTags"
                    :key="tag.id"
                    closable
                    @close="removeTag(tag.id)"
                    class="tag-item"
                  >
                    {{ tag.name }}
                  </el-tag>
                  <el-button
                    type="text"
                    size="small"
                    @click="showAddTagDialog"
                  >
                    + 添加标签
                  </el-button>
                </div>
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
  </div>
  <div v-else class="photo-detail-empty">
    <el-empty description="未选择照片" />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue';
import { ElButton, ElIcon, ElTabs, ElTabPane, ElEmpty, ElInput, ElTag, ElMessage } from 'element-plus';
import { 
  FolderOpened, 
  View, 
  Star, 
  Loading, 
  Location 
} from '@element-plus/icons-vue';
import type { Photo, Tag, ExifInfo } from '@/types';
import { photoService } from '@/services/photoService';

interface Props {
  photo: Photo | null;
}

const props = defineProps<Props>();

// 当前激活的标签页
const activeTab = ref('basic');
// 图片加载状态
const imageLoading = ref(true);
// 照片描述
const photoDescription = ref('');
// 照片标签
const photoTags = ref<Tag[]>([]);

// EXIF信息（从photo对象中提取或从服务获取）
const exifInfo = computed<ExifInfo>(() => {
  if (!props.photo) return {};
  
  // 这里应该从photo对象中获取EXIF信息
  // 或者通过服务获取完整的EXIF信息
  return props.photo.exifInfo || {};
});

// 是否有相机信息
const hasCameraInfo = computed(() => {
  return !!(props.photo?.cameraMake || 
            props.photo?.cameraModel || 
            exifInfo.value.focalLength || 
            exifInfo.value.aperture || 
            exifInfo.value.shutterSpeed || 
            exifInfo.value.iso || 
            exifInfo.value.flash);
});

// 是否有位置信息
const hasLocationInfo = computed(() => {
  return !!(props.photo?.latitude && props.photo?.longitude);
});

// 监听photo变化，更新相关数据
watch(() => props.photo, (newPhoto) => {
  if (newPhoto) {
    photoDescription.value = newPhoto.description || '';
    // 获取照片标签
    loadPhotoTags(newPhoto.id);
    imageLoading.value = true;
  } else {
    photoDescription.value = '';
    photoTags.value = [];
  }
}, { immediate: true });

// 获取预览图URL
const getPreviewUrl = (photo: Photo) => {
  if (photo.previewPath) {
    return `file://${photo.previewPath}`;
  }
  return `file://${photo.filePath}`;
};

// 处理图片加载完成
const handleImageLoad = () => {
  imageLoading.value = false;
};

// 处理图片加载错误
const handleImageError = () => {
  imageLoading.value = false;
  ElMessage.error('图片加载失败');
};

// 在文件夹中显示
const openInFolder = async () => {
  if (!props.photo) return;
  
  try {
    await photoService.showInFolder(props.photo.filePath);
  } catch (error) {
    ElMessage.error('无法在文件夹中显示');
  }
};

// 使用默认应用打开
const openWithDefaultApp = async () => {
  if (!props.photo) return;
  
  try {
    await photoService.openWithDefaultApp(props.photo.filePath);
  } catch (error) {
    ElMessage.error('无法使用默认应用打开');
  }
};

// 切换收藏状态
const toggleFavorite = async () => {
  if (!props.photo) return;
  
  try {
    const newRating = props.photo.rating > 0 ? 0 : 5;
    await photoService.updatePhoto(props.photo.id, { rating: newRating });
    ElMessage.success(newRating > 0 ? '已添加到收藏' : '已取消收藏');
  } catch (error) {
    ElMessage.error('操作失败');
  }
};

// 格式化日期时间
const formatDateTime = (dateString: string) => {
  if (!dateString) return '未知';
  const date = new Date(dateString);
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  });
};

// 格式化文件大小
const formatFileSize = (bytes: number) => {
  if (!bytes) return '未知';
  
  const units = ['B', 'KB', 'MB', 'GB'];
  let size = bytes;
  let unitIndex = 0;
  
  while (size >= 1024 && unitIndex < units.length - 1) {
    size /= 1024;
    unitIndex++;
  }
  
  return `${size.toFixed(1)} ${units[unitIndex]}`;
};

// 格式化坐标
const formatCoordinate = (latitude: number, longitude: number) => {
  const lat = latitude >= 0 ? `${latitude.toFixed(6)}°N` : `${Math.abs(latitude).toFixed(6)}°S`;
  const lng = longitude >= 0 ? `${longitude.toFixed(6)}°E` : `${Math.abs(longitude).toFixed(6)}°W`;
  return `${lat}, ${lng}`;
};

// 加载照片标签
const loadPhotoTags = async (photoId: string) => {
  try {
    photoTags.value = await photoService.getPhotoTags(photoId);
  } catch (error) {
    console.error('加载照片标签失败:', error);
  }
};

// 更新照片描述
const updateDescription = async () => {
  if (!props.photo) return;
  
  try {
    await photoService.updatePhoto(props.photo.id, { description: photoDescription.value });
    ElMessage.success('描述已更新');
  } catch (error) {
    ElMessage.error('更新描述失败');
  }
};

// 移除标签
const removeTag = async (tagId: string) => {
  if (!props.photo) return;
  
  try {
    await photoService.removePhotoTag(props.photo.id, tagId);
    photoTags.value = photoTags.value.filter(tag => tag.id !== tagId);
    ElMessage.success('标签已移除');
  } catch (error) {
    ElMessage.error('移除标签失败');
  }
};

// 显示添加标签对话框
const showAddTagDialog = () => {
  // 这里应该显示一个添加标签的对话框
  // 可以使用ElMessageBox或自定义组件
  ElMessage.info('添加标签功能待实现');
};
</script>

<style scoped lang="scss">
.photo-detail {
  display: flex;
  flex-direction: column;
  height: 100%;
  
  .detail-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px;
    border-bottom: 1px solid var(--el-border-color-light);
    
    .photo-title {
      font-size: 18px;
      font-weight: 500;
      color: var(--el-text-color-primary);
      max-width: 50%;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
    
    .photo-actions {
      display: flex;
      gap: 8px;
      
      .is-favorite {
        color: var(--el-color-warning);
      }
    }
  }
  
  .detail-content {
    display: flex;
    flex: 1;
    overflow: hidden;
    
    .photo-preview {
      flex: 1;
      display: flex;
      align-items: center;
      justify-content: center;
      background-color: var(--el-fill-color-lighter);
      position: relative;
      
      img {
        max-width: 100%;
        max-height: 100%;
        object-fit: contain;
      }
      
      .image-loading-overlay {
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        display: flex;
        align-items: center;
        justify-content: center;
        background-color: rgba(255, 255, 255, 0.7);
        
        .el-icon {
          font-size: 24px;
          color: var(--el-color-primary);
        }
      }
    }
    
    .photo-info {
      width: 350px;
      border-left: 1px solid var(--el-border-color-light);
      overflow: hidden;
      display: flex;
      flex-direction: column;
      
      .el-tabs {
        height: 100%;
        display: flex;
        flex-direction: column;
        
        :deep(.el-tabs__content) {
          flex: 1;
          overflow-y: auto;
        }
      }
      
      .info-section {
        padding: 16px;
        
        .info-item {
          margin-bottom: 16px;
          
          &:last-child {
            margin-bottom: 0;
          }
          
          .info-label {
            font-size: 12px;
            color: var(--el-text-color-secondary);
            margin-bottom: 4px;
          }
          
          .info-value {
            font-size: 14px;
            color: var(--el-text-color-primary);
            word-break: break-all;
            
            &.file-path {
              font-family: monospace;
              font-size: 12px;
              background-color: var(--el-fill-color-light);
              padding: 4px 8px;
              border-radius: 4px;
            }
          }
          
          .tag-item {
            margin-right: 8px;
            margin-bottom: 8px;
          }
        }
        
        .map-container {
          margin-top: 16px;
          height: 200px;
          border-radius: 8px;
          overflow: hidden;
          
          .map-placeholder {
            height: 100%;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            background-color: var(--el-fill-color-light);
            color: var(--el-text-color-secondary);
            
            .el-icon {
              font-size: 32px;
              margin-bottom: 8px;
            }
            
            .coordinates {
              font-size: 12px;
              margin-top: 4px;
              font-family: monospace;
            }
          }
        }
      }
    }
  }
}

.photo-detail-empty {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
}

// 响应式设计
@media (max-width: 768px) {
  .photo-detail {
    .detail-header {
      flex-direction: column;
      align-items: flex-start;
      gap: 8px;
      
      .photo-title {
        max-width: 100%;
      }
    }
    
    .detail-content {
      flex-direction: column;
      
      .photo-preview {
        height: 300px;
      }
      
      .photo-info {
        width: 100%;
        border-left: none;
        border-top: 1px solid var(--el-border-color-light);
      }
    }
  }
}
</style>